const express = require('express')
const router = express.Router()
const userModel = require('../models/user')
const Token = require('../Token.js')
router.get("/", (req, res, next) => {
    let token = req.headers.authorization
    let { username, password } = req.query
    userModel.find({ username: username }, function (err, data) {
        if (!err) {
            let mypsw = data[0].password
            if (password != mypsw){
                res.end('wrongpsw')
            }
            else if (password == mypsw) {
                if (token == 'null') {
                    //加密
                    let mytoken = Token.encrypt(username)
                    console.log(mytoken)
                    //返回状态为0表示还未获取token的首次登录
                    let resobj = { 'status': 0, 'token': mytoken, 'data': data }
                    res.end(JSON.stringify(resobj))
                }
                else if (token != 'null') {
                    console.log(token)
                    //解密
                    let mytoken = Token.decrypt(token).mytoken
                    console.log(mytoken, username)
                    if (mytoken == username) {
                        //返回状态为1表示token验证成功
                        let resobj = { 'status': 1, 'username': username, 'data': data }
                        res.end(JSON.stringify(resobj))
                        next()
                    }
                    else {
                        let resobj = { 'status': 2, 'username': username, 'data': data }
                        res.end(JSON.stringify(resobj))
                    }
                }
            }

        }
        else {
            res.end('error')
        }
    })

    console.log(req.query)

})
module.exports = router